//=============================================================================
#include "CApp.h"

//=============================================================================
bool CApp::OnInit() {
    if(SetConsoleCtrlHandler((PHANDLER_ROUTINE)CApp::ConsoleHandler, true) == false) {
        CLog::Error("Unable to hook Ctrl Handler");
        return false;
    }

    if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        CLog::Error("Unable to Init SDL");
        return false;
    }

    if(SDLNet_Init() < 0) {
        CLog::Error("Unable to initialize SDL_net : " + cStringify(SDL_GetError()));
        return false;
    }

    if(FE_Init() == -1) {
        return FE_GetError();
    }

    if(NET2_Init() == -1) {
        return NET2_GetError();
    }

    freopen("CON", "w", stdout);
    freopen("CON", "w", stderr);

    if(CSystem::ParseConfig() == false) {
        CLog::Error("Unable to parse Configuration file (missing or parse error)");
        return false;
    }

    std::string PortString = CSystem::GetConfigValue("Port");
    int Port = atoi(PortString.c_str());

    NET2_TCPAcceptOn(Port);

    CLog::Notice("Network Started, Listening on Port " + PortString);

    std::string WorldDirectory  = CSystem::GetConfigValue("WorldDirectory");
    std::string ServerScript    = CSystem::GetConfigValue("ServerScript");

    chdir(WorldDirectory.c_str());

    CLog::Notice("World Directory set as : " + WorldDirectory);
    CLog::Notice("Server Script set as : " + ServerScript);

	if(CLua::LuaControl.OnInit() == false) {
	    CLog::Error("Unable to Init Lua");
	    return false;
	}

	if(CLua::LuaControl.OnLoad(ServerScript) == false) {
	    CLog::Error("Server Script '" + ServerScript + "' file found or parse error");
	    return false;
	}

    CLua::LuaControl.PushFunction("OnInit");
    CLua::LuaControl.Call();

	return true;
}

//=============================================================================
